import axiosInstance from './axiosInstance';

interface AddToCartData {
  productId: number;
  quantity: number;
}

interface UpdateCartItemData {
  quantity: number;
}

// 定义购物车项的类型
interface CartItem {
  id: number;
  userId: number;
  productId: number;
  quantity: number;
  unitPrice: number;
  createdAt: string;
  updatedAt: string;
  product: {
    id: number;
    name: string;
    images: string[];
    stock: number;
    price: number;
    isActive: boolean;
    category: {
      id: number;
      name: string;
    };
  };
  availableQuantity: number;
  priceChanged: boolean;
  currentPrice: number;
  subtotal: string;
}

// 定义获取购物车响应的类型
interface GetCartResponse {
  success: boolean;
  data: {
    cartItems: CartItem[];
    summary: {
      totalItems: number;
      totalPrice: string;
      itemCount: number;
    };
  };
}

export const cartService = {
  // 添加商品到购物车
  addToCart: async (data: AddToCartData) => {
    return axiosInstance.post('/cart', data);
  },

  // 获取购物车
  getCart: async (): Promise<GetCartResponse> => {
    return axiosInstance.get('/cart');
  },

  // 更新购物车商品数量
  updateCartItem: async (itemId: number, data: UpdateCartItemData) => {
    return axiosInstance.put(`/cart/${itemId}`, data);
  },

  // 从购物车移除商品
  removeFromCart: async (itemId: number) => {
    return axiosInstance.delete(`/cart/${itemId}`);
  },

  // 清空购物车
  clearCart: async () => {
    return axiosInstance.delete('/cart');
  }
};

// 单独导出 addToCart 函数，以便直接解构导入
export const addToCart = cartService.addToCart;
// 也可以为其他常用函数添加单独导出
export const getCart = cartService.getCart;
export const updateCartItem = cartService.updateCartItem;
export const removeFromCart = cartService.removeFromCart;
export const clearCart = cartService.clearCart;